package org.popupcommunication.dao.impl;



import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.popupcommunication.dao.GenericRepository;
import org.springframework.transaction.annotation.Transactional;



import java.lang.reflect.ParameterizedType;
import java.util.List;

@Transactional
//@Repository
public abstract class GenericRepositoryJpa<T> implements GenericRepository<T>{

	@PersistenceContext(unitName = "MaBaseMysql")
	private EntityManager em;

	public EntityManager getEntityManager() {
		return em;
	}

	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	private Class<T> persistenceClass;

	@SuppressWarnings("unchecked")
	public GenericRepositoryJpa() {
		this.persistenceClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}


	public void add(T item) {
		// TODO Auto-generated method stub
		em.persist(item);

	}
	
	public T merge(T item){
		return em.merge(item);
	}

	public void delete(T item) {
		// TODO Auto-generated method stub
		em.remove(em.merge(item));
	}

	public T save(T item) {
		// TODO Auto-generated method stub
		return em.merge(item);
	}


	public List<T> findAll() {
		TypedQuery<T> q = em.createNamedQuery(persistenceClass.getSimpleName()
				+ ".findAll", persistenceClass);

		return q.getResultList();
	}

	public T findById(int id) {
		// TODO Auto-generated method stub
		return em.find(persistenceClass, id);
	}
}
